package com.green.web.controller;


import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.green.common.ContextHolder;
import com.green.common.util.SecurityMD5Util;
import com.green.common.util.StringUtil;
import com.green.dao.cache.XMemcachedCache;
import com.green.model.manage.AreaPermission;
import com.green.model.manage.Org;
import com.green.model.manage.Person;
import com.green.service.common.ServiceContext;
import com.green.service.manage.AreaPermissionService;
import com.green.service.manage.DataPermissionService;
import com.green.service.manage.FunPermissionService;
import com.green.service.manage.PersonService;
import com.green.web.util.Constants;
import com.green.web.util.PermissionHelper;
import com.green.web.util.SessionHelper;
import com.green.web.util.WebContext;


/**
 * 登录
 * 
 */
@Controller
@RequestMapping(value = "/login/*")
public class LoginController extends BaseController {
	@Resource
	private PersonService personService;
	@Resource
	private AreaPermissionService areaPermissionService;

	@Autowired
	private XMemcachedCache memcachedClient;
	
	@Resource
	private DataPermissionService dataPermissionService;
		
	@Resource
	private FunPermissionService funPermissionService;

	@RequestMapping(value = "toLogin")
	public String load(ModelMap modelMap, HttpServletResponse response, HttpServletRequest request) {

		Person person = (Person) SessionHelper.getAttribute(Constants.CURRENT_PERSON);
		//已登陆跳转
			if(person!=null){
				/*//表示已经登陆  直接跳转到首页
				modelMap.put("optCodes", PermissionHelper.getOperateCodes());
				modelMap.put("person", person);
				//默认城市
				if(null!=person.getCityName()){
					String [] cityName =person.getCityName().split(",");
					  modelMap.put("cityName", cityName);
					modelMap.put("city", WebContext.getCurrentCity());
				}			*/
				return "MiddenOpenNewWindow";
			}
		return "Login";
	}
	
	/**
	 * 获取已经登录的用户信息
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	private Map<String, String> getLoginedUser(HttpServletRequest request){
		//XMemcachedCache memcachedClient = BeanFactory.getBean("xMemcachedCache");//4657r6zgekj17bo3afrfnr1u
		Cookie[] cookies = request.getCookies();
		String sessionId=request.getSession().getId();
		if (cookies != null) {
		    for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (cookie.getName().equalsIgnoreCase("COMMONSESSION")) {
					sessionId=cookie.getValue();
				}
		    }			
		}
		Map<String, String> userInfo = (Map<String, String>) memcachedClient.get(sessionId);
		return userInfo;
	}

	@SuppressWarnings("unused")
	private void clearCookie(HttpServletResponse response, HttpServletRequest request) {

		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie tmpCookie : cookies) {
				if ("cookieUserId".equals(tmpCookie.getName())) {
					tmpCookie.setValue(null);
					tmpCookie.setMaxAge(0);
					response.addCookie(tmpCookie);
				}
			}
		}

		request.getSession().invalidate();
	}

	@RequestMapping(value = "validation")
	public String validattion(ModelMap modelMap, HttpServletResponse response) {
		Person person = null;
		String dataBase = getString("dataBase");
		String userName = getString("userName");
		String password = getString("password");

		if (StringUtil.isEmpty(userName)) {
			modelMap.put("msg", "帐号或密码错误，请重试。");
			modelMap.put("userName",userName);
			return "Login";
		}    
		if(!StringUtil.isEmpty(password) && "密码".equals(password)){
			password=null;
		}			
		if (StringUtils.isNotEmpty(userName)) {
			userName = userName.trim();
		}
		modelMap.put("dataBase", dataBase);
		modelMap.put("userName", userName);
		modelMap.put("password", password);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", userName);
		if (null != password && !"".equals(password)) {
			try {
				password = SecurityMD5Util.getInstance().MD5Encode(password);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			map.put("password", password);
		} else {
			map.put("password", "");
		}
		ContextHolder.setDataSource(dataBase);
		List<Person> list = null;
		
		list = personService.getLoginUser(map);		
		if (null != list && list.size() > 0) {
			person = list.get(0);
			
			
			if (person.getIsForbidden() == 1) {
				modelMap.put("msg", "用户已禁用");
				modelMap.put("userName",userName);
				return "Login";
			}
			if (person.getIsForbidden() == 0) {	
				person = personService.getPersonById(person.getId());	
				
				
				//数据查看权限
				Map<String, Object> param = new HashMap<String, Object>();		
				param.put("personId", person.getId());			
				
				if(!userName.contains("admin"))
				{
					/*Org org=orgService.getOrgById(person.getControUnit().getId());//控制单元
					if(org.getNumber().equals(Constant.JMSYB_NUMBER)){
						 Map<String, Object> params = new HashMap<String, Object>();
						 params.put("orgType", OrgEnum.COMPANY);
						 params.put("longNumberLogin", person.getOrg().getLongNumber());
						 List<Org> orgList =orgService.getOrgList(params);
						 if(null!=orgList&&orgList.size()>0){
						    person.setControUnit(orgService.getOrgList(params).get(0));
						 }
					 }*/
				//没有分配不能进入系统
				List<AreaPermission> areapList=areaPermissionService.getAreaPermissionList(param);				
					if(null==areapList||areapList.size()<=0){
						modelMap.put("msg", "未分配区域，暂时无法登陆");
						return "Login";
					}
			    
				}
				ServiceContext.setLoginPerson(person);
				SessionHelper.create(person.getId());
				SessionHelper.setAttribute(Constants.CURRENT_PERSON, person);
				
				List<Org> dataList=dataPermissionService.getDataPermissionLoin(param);
				if(null==dataList||dataList.size()<=0){
					param.clear();
					param.put("positionId", person.getPosition().getId());
					dataList=dataPermissionService.getDataPermissionLoin(param);
				}
				PermissionHelper.setDataPermissionList(dataList);				
				//模块负责
				//PermissionHelper.setAreaPermissionList(areaPermissionService.getAreaPermissionList(param));
				param.clear();
				//操作权限项
				param.put("positionId", person.getPosition().getId());
				PermissionHelper.setFunPermissionList(funPermissionService.getFunPermissionList(param));
				//默认城市
				if(null!=person.getCityName()){
					String [] cityName =person.getCityName().split(",");
					//modelMap.put("cityName", cityName);
					//modelMap.put("city", cityName[0]);
					if(null!=cityName&&cityName.length>=0){	
						WebContext.setCurrentCity(cityName[0]);
					}
				}			
				
				//表示已经登陆  直接跳转到首页
				//modelMap.put("optCodes", PermissionHelper.getOperateCodes());
				//modelMap.put("person", person);
				
				return "MiddenOpenNewWindow";
			}
		} else {
			modelMap.put("msg", "用户名或密码不正确");
			return "Login";
		}
		return null;
	}

	@RequestMapping("exit")
	public String exitSystem(HttpServletRequest request, HttpServletResponse response) {
		try {
			SessionHelper.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "Login";
	}
	@RequestMapping("setCity")
	@ResponseBody
	public Map<String, Object> setCity(HttpServletRequest request, HttpServletResponse response) {
		WebContext.setCurrentCity(getString("city"));	
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("message", 1);
		result.put("currentCityName", getString("city"));
		return result;
	}
	 //我的工作台
	@RequestMapping(value = "/workPlatform")
	public String myWorkPlatform(ModelMap modelMap) {
		Person person = (Person) SessionHelper.getAttribute(Constants.CURRENT_PERSON);
		if(person!=null){
			//表示已经登陆  直接跳转到首页
			modelMap.put("optCodes", PermissionHelper.getOperateCodes());
			modelMap.put("person", person);
			//默认城市
			if(null!=person.getCityName()){
				String [] cityName =person.getCityName().split(",");
				modelMap.put("cityName", cityName);
				modelMap.put("city", WebContext.getCurrentCity());
			}		
			return "Index";
		}else{
			return "Login";
		}
		
	}
	 //我的工作台
	@RequestMapping(value = "/overtime")
	public String overtime(ModelMap modelMap) {
		
			return "Overtime";		
		
	}
}
